package cn.jolyoulu.common.web.utils;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import cn.jolyoulu.common.web.entity.ResultInfo;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.CharEncoding;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;
import java.util.zip.ZipOutputStream;

/**
 * @Author: JolyouLu
 * @Date: 2023/1/21 15:52
 * @Description Response 请求处理类
 */
@Slf4j
public class ResponseUtils {

    private ResponseUtils() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 返回Json结果给前端
     *
     * @param response   response
     * @param resultInfo 结果内容
     */
    public static void outJson(HttpServletResponse response, ResultInfo resultInfo) {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.println(JSONObject.toJSONString(resultInfo));
        } catch (IOException e) {
            log.error("返回结果失败", e);
        }
    }

    /**
     * 返回二进制流结果给前端
     *
     * @param response response
     * @param stream   流
     */
    public static void outStream(HttpServletResponse response, byte[] stream) {
        response.setStatus(200);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        try (ServletOutputStream os = response.getOutputStream()) {
            os.write(stream);
        } catch (IOException e) {
            log.error("返回结果失败", e);
        }
    }

    /**
     * 下载zip
     *
     * @param response response
     * @param fileName 文件名
     * @param consumer 对流进行操作
     * @throws IOException
     */
    public static void outZip(HttpServletResponse response, String fileName, Consumer<ZipOutputStream> consumer) {
        response.setStatus(200);
        response.setContentType("application/x-msdownload");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".zip");
        try (ServletOutputStream os = response.getOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(os)) {
            consumer.accept(zipOut);
        } catch (IOException e) {
            log.error("返回结果失败", e);
        }
    }

    /**
     * 切换response为Excel下载模式
     *
     * @param response response
     * @param fileName 文件名 xxx.xlsx xxx.xls
     */
    public static void outExcelMode(HttpServletResponse response, String fileName) {
        if(fileName.endsWith("xlsx")){
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }else {
            response.setContentType("application/vnd.ms-excel");
        }
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        //设置额外的响应头，兼容不同浏览器
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-Control", "no-cache, must-revalidate");
        response.setDateHeader("Expires", 0);
    }
}
